#include "basexml.h"

BaseXml::BaseXml()
{
	m_doc = NULL;
}

BaseXml::~BaseXml()
{
	if(this->m_doc)
	{
		xmlFreeDoc(this->m_doc);
	}
}

/// 解析来自于文件中的XML内容
bool BaseXml::loadXML(const std::string& filename)
{
#ifdef XMLLIB2_DEBUG
	std::cout << "XMLLib2::loadXML" << std::endl;
#endif
	xmlDocPtr doc;
	doc = xmlReadFile(filename.c_str(),NULL,0);
	if(NULL == doc)
	{
		this->m_doc = NULL;
		return false;
	}

	this->m_doc = doc;
	return true;
}

/// 解析来自于内存的XML内容
bool BaseXml::readXML(const std::string& content)
{
#ifdef XMLLIB2_DEBUG
	std::cout << "XMLLib2::readXML" << std::endl;
#endif
	size_t iLength = content.size();
	xmlDocPtr doc;
	doc = xmlReadMemory(content.c_str(), iLength, "UTF-8", NULL, 0);
	if(NULL == doc)
	{
		this->m_doc = NULL;
		return false;
	}

	this->m_doc = doc;
	return true;
}

/// 得到根节点指针
xmlNodePtr BaseXml::GetRootNode()
{

    xmlNodePtr curNode;
    curNode = xmlDocGetRootElement(m_doc);
    if (NULL != curNode)
    {
        return curNode;
    }
    return NULL;
}

const char* BaseXml::GetNodeName(xmlNodePtr node)
{
	if (!node)
		return "";
	return (const char*)node->name;
}

xmlNodePtr BaseXml::GetChildNode(xmlNodePtr parentnode, const char* NodeText)
{
    if(!parentnode)
        return NULL;
    xmlNodePtr curNode=parentnode->xmlChildrenNode;
    while(curNode != NULL)
    {
        if ((!xmlStrcmp(curNode->name, (const xmlChar *)NodeText)))
        {
            return curNode;
        }
        curNode = curNode->next;
    }
    return NULL;
}

std::string BaseXml::GetNodeAttr(xmlNodePtr curNode, const char* AttrText)
{
	std::string res;
   if(!curNode)
    return res;
     xmlAttrPtr attrPtr = curNode->properties;
    while (attrPtr != NULL)
    {
        if (!xmlStrcmp(attrPtr->name, (const xmlChar *)AttrText))
        {
            xmlChar* szAttr = xmlGetProp(curNode,(const xmlChar *)AttrText);
            res=(char*)szAttr;
            xmlFree(szAttr);
            break;
        }
        attrPtr = attrPtr->next;
    }
    return res;
}

std::string BaseXml::GetNodeText(xmlNodePtr curNode)
{
	std::string res;
	if(curNode)
	{
		xmlChar* szKey = xmlNodeGetContent(curNode);
		res=(char*)szKey;
		xmlFree(szKey);
	}
	return res;
}
